import json
import re

from django.conf import settings
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.mail import send_mail
from django.http import HttpResponseBadRequest,HttpResponse
from django import http
from django.shortcuts import render, redirect
from django_redis import get_redis_connection

from django.views import View

from qingmei_mall.utils.merge_cart import merge_cart_cookie_to_redis
from qingmei_mall.utils.response_code import  RETCODE
from qingmei_mall.utils import  secret_openid
from users.models import User, Address


#用户注册
class Regist(View):
    def get(self,request):
        return render(request,'register.html')

    def post(self,request):
        #接收
        user_name= request.POST.get('user_name')
        pwd= request.POST.get('pwd')
        cpwd= request.POST.get('cpwd')
        phone=request.POST.get('phone')
        peaer=request.POST.get('msg_code')

        #验证 （返回错误处理）
            #非空验证
        if not all([user_name,pwd,cpwd,phone]):
            return HttpResponseBadRequest('you cant notnull')
            #用户验证
        if not(re.match('^[a-zA-Z0-9_-]{5,20}$',user_name)):
            return HttpResponseBadRequest('用户名格式错误')
            #密码验证
        if not (re.match('^[0-9A-Za-z]{8,20}$',pwd)):
            return HttpResponseBadRequest('密码格试错误')
            #确定密码
        if not pwd==cpwd:
            return HttpResponseBadRequest('请确认密码是否正确')
            #手机号确认
        if not (re.match('^1[345789]\d{9}$',phone)):
            return HttpResponseBadRequest("手机号输入错误")

            #短信验证
        Get_peaer_redis=get_redis_connection('imagecode')
        sms_peaer=Get_peaer_redis.get('sms_'+phone)
        if sms_peaer is None:
            return render(request,'register.html',{'code':RETCODE.IMAGECODEERR,'errmsg':'短信验证码错误'})
        if sms_peaer.decode() !=peaer:
            return render(request, 'register.html', {'code': RETCODE.IMAGECODEERR, 'errmsg': '短信验证码不匹配'})
        Get_peaer_redis.delete('sms_'+phone)
        #处理
        user=User.objects.create_user(username=user_name,password=pwd,mobile=phone)

        #响应
        login(request,user)
        response = redirect('/')
        response.set_cookie('username', request.user.username)

        return response

#功能：校验用户名
class CheckUser(View):
    def get(self,request,username):
        count=User.objects.filter(username=username).count()

        return http.JsonResponse({'code':200,'errmsg':'ok','count':count})
#功能：校验手机号

class Phone(View):
    def get(self, request, mobile):
        count=User.objects.filter(mobile=mobile).count()
        return http.JsonResponse({'code':200,'errmsg':'ok','count':count})

#登陆界面
class LoginView(View):
    def get(self,request):
        return render(request,'login.html',)
    def post(self,request):
        user_name = request.POST.get('username')
        pwd = request.POST.get('pwd')
        remember=request.POST.get('remebered')
        next_url=request.GET.get('next','/')
        username=User.objects.filter(username=user_name)
        if not all([user_name, pwd]):
            return HttpResponseBadRequest('用户或密码错误')
        if not (username):
            return http.HttpResponseBadRequest('请注册')
            # 用户验证
        if not (re.match('^[a-zA-Z0-9_-]{5,20}$', user_name)):
            return HttpResponseBadRequest('用户名格式错误')
            # 密码验证
        if not (re.match('^[0-9A-Za-z]{8,20}$', pwd)):
            return HttpResponseBadRequest('密码格试错误')

        user=authenticate(username=user_name,password=pwd)
        if user:
            login(request,user)
            #写入cookie
            response=redirect(next_url)
            response = merge_cart_cookie_to_redis(request,response)

            if remember :
                request.session.set_expiry(None)  #set_expiry过期时间 none两周
                #登录
                response.set_cookie('username', request.user.username,max_age=3600 * 24 * 15)
                return response

            else:
                request.session.set_expiry(0)
                #登录
                response.set_cookie('username', request.user.username)
                return response

        else:
            return render(request,'login.html',{"loginerror":'用户名或密码错误'})


#用户退出
class LogoutView(View):
    def get(self,request):
        # 处理
        logout(request)
        #  清除cookie
        response = redirect("/")
        response.delete_cookie("username")
        # 响应
        return response

#用户中心
class InfoView(LoginRequiredMixin,View):  #LoginRequiredMixin类判定点击用户中心时是否已登路
    def get(self,request):

        user=request.user

        contset={
        'username': user.username,
        'mobile': user.mobile,
        'email': user.email,
        'email_active': user.email_avtive,
        }


        # if request.user.is_authenticated:
        return render(request,'user_center_info.html',context=contset)
        # return redirect('/login/')

#保存邮箱
class EmailView(View):
    def put(self,request):
        #接收
        json_emali=json.loads(request.body.decode())
        email=json_emali.get('email')

        #验证
        if not email:
            return http.HttpResponseForbidden('未填写邮箱')


        #处理
        try:
            user=request.user
            user.email = email
            user.save()
            print(email)
            title='美多商城'
            message = ''
            send_man = settings.EMAIL_FROM
            save_man=[email]

            # 加密
            email_token = secret_openid.dump_(user.id,60*60*24*7)
            EMAIL_VERIFY_URL = 'http://www.meiduo.site:8000/emails/verification/'+'?token=' + email_token

            html_message = '<p>尊敬的用户您好！</p>' \
                           '<p>感谢您使用清美商城。</p>' \
                           '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                           '<p><a href="%s">%s<a></p>' % (send_man, EMAIL_VERIFY_URL, EMAIL_VERIFY_URL)
            send_mail(title,message,send_man,save_man,html_message=html_message)
            # user.email_avtive=1

        except:
            return http.JsonResponse({'code':RETCODE.DBERR,'errmsg':'添加失败'})
        return http.JsonResponse({'code':RETCODE.OK,'errmsg':'添加成功'})


#邮箱验证
class EmailsVerification(View):
    def get(self,request):
        #接受
        email_token=request.GET.get('token')
        #处理
        #解密
        token_load=secret_openid.load_(email_token)
        #验证
        if not token_load:
            return http.HttpResponseForbidden('token错误')


        user=User.objects.get(pk=token_load)
        print(user)
        user.email_avtive=1
        user.save()
        return redirect('/info/')
        #响应



class CreateView(LoginRequiredMixin,View):

    def post(self,request):
        #接受
        address=json.loads(request.body.decode())
        receiver=address.get('receiver')
        province_id=address.get('province_id')
        city_id=address.get('city_id')
        place = address.get('place')
        district_id=address.get('district_id')
        mobile= address.get('mobile')
        tel=address.get('tel')
        email=address.get('email')
        #验证
        if not all([receiver, province_id, city_id, district_id, mobile]):
            return http.HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('参数mobile有误')
        if not re.match(r'^1[3-9]\d{9}$', tel):
            return http.HttpResponseForbidden('参数tel有误')
        #处理

        address_user=Address.objects.create(
            user=request.user,
            title=receiver,
            receiver=receiver,
            province_id=province_id,
            city_id=city_id,
            district_id=district_id,
            place=place,
            mobile=mobile,
            tel=tel,
            email=email,
        )




        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'address':{

            'id': address_user.id,
            'receiver': address_user.receiver,
            'province': address_user.province.name,
            'province_id': province_id,
            'city': address_user.city.name,
            'city_id': city_id,
            'district': address_user.district.name,
            'district_id': district_id,
            'place': place,
            'mobile': mobile,
            'tel': tel,
            'email': email
        }})



#展示收获地址
class AddressView(View):
    def get (self,request) :
        user=request.user
        addresss=Address.objects.filter(is_deleted=False)
        address_list=[]
        for address in addresss:

            address_dict = {
                'id': address.id,
                'title':address.receiver,
                'receiver': address.receiver,
                'province': address.province.name,
                'province_id': address.province.id,
                'city': address.city.name,
                'city_id': address.city.id,
                'district': address.district.name,
                'district_id': address.district.id,
                'place': address.place,
                'mobile': address.mobile,
                'tel': address.tel,
                'email': address.email
            }
            address_list.append(address_dict)

        context = {
            'default_address_id': user.default_address_id,
            'addresses': address_list,
        }
        return render(request,'user_center_site.html',context)


#修改,更新
class UpdateDestroyAddressView(LoginRequiredMixin,View):

    def put(self,request,address_id):
        #接受
        address=json.loads(request.body.decode())
        receiver=address.get('receiver')
        province_id=address.get('province_id')
        city_id=address.get('city_id')
        place = address.get('place')
        district_id=address.get('district_id')
        mobile= address.get('mobile')
        tel=address.get('tel')
        email=address.get('email')
        #验证
        if not all([receiver, province_id, city_id, district_id, mobile]):
            return http.HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('参数mobile有误')
        if not re.match(r'^1[3-9]\d{9}$', tel):
            return http.HttpResponseForbidden('参数tel有误')
        #处理
        try:
            Address.objects.filter(id=address_id).update(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )

        except:
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '更新地址失败'})

        address_user=Address.objects.get(id=address_id)

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'address':{

            'id': address_user.id,
            'receiver': address_user.receiver,
            'province': address_user.province.name,
            'province_id': province_id,
            'city': address_user.city.name,
            'city_id': city_id,
            'district': address_user.district.name,
            'district_id': district_id,
            'place': place,
            'mobile': mobile,
            'tel': tel,
            'email': email
        }})

    def delete(self, request, address_id):
        """删除地址"""
        try:
            # 查询要删除的地址
            address = Address.objects.get(id=address_id)

            # 将地址逻辑删除设置为True
            address.is_deleted = True
            address.save()



        except :

            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '删除地址失败'})

        # 响应删除地址结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '删除地址成功'})


class DefualtAera(LoginRequiredMixin,View):
    def put (self,request,address_id):


        address=Address.objects.get(id=address_id)
        request.user.default_address=address
        request.user.save()


        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '设置默认地址成功','default_address_id':address_id})

class TitleView(View):
    def put(self,request,address_id):
        address_all=json.loads(request.body.decode())
        title=address_all.get('title')

        title_Address=Address.objects.get(id=address_id)
        title_Address.title=title
        title_Address.save()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '设置地址标题成功'})



class ChangePasswordView(LoginRequiredMixin, View):
    """修改密码"""

    def get(self, request):
        """展示修改密码界面"""
        return render(request, 'user_center_pass.html')

    def post(self,request):
        old_password = request.POST.get('old_pwd')
        new_password = request.POST.get('new_pwd')
        new_password2 = request.POST.get('new_cpwd')

        if not all([old_password, new_password, new_password2]):
            return http.HttpResponseForbidden('缺少必传参数')
        if not request.user.check_password(old_password):
            return render(request, 'user_center_pass.html', {'origin_pwd_errmsg': '原始密码错误'})
        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return http.HttpResponseForbidden('密码最少8位，最长20位')
        if new_password != new_password2:
            return http.HttpResponseForbidden('两次输入的密码不一致')

        request.user.set_password(new_password)
        request.user.save()

        logout(request)   #状态退出
        response=render(request,'login.html')  #删除cookie
        response.delete_cookie('username')

        return response
